package cn.tedu.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 发布订阅
 */
public class RoutingMode {
    /**
     * 实现生产端或消费端之前，创建连接对象
     */
    Channel channel;
    String ip = "10.42.182.184";
    int port = 5672;
    String userName = "guest";
    String password = "guest";

    /**
     * 交换机类型
     */
    static final String type = "direct";
    /**
     * 交换机名称
     */
    static final String exName = type + "Exchange";

    static final String q1 = "queue01" + type;
    static final String q2 = "queue02" + type;

    @Before
    public void initChannel() {
        // 获取连接工厂对象，赋值连接信息 ip/port/userpassword/virtual host
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(ip);
        factory.setPort(port);
        // 默认值
//        factory.setUsername(userName);
//        factory.setPassword(password);
//        factory.setVirtualHost("/");
        try {
            Connection connection = factory.newConnection();
            channel = connection.createChannel();
        } catch (TimeoutException timeoutException) {
            timeoutException.printStackTrace();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }

    /**
     * 生产端逻辑
     */
    @Test
    public void send() {
        // 准备一个即将发送的消息字符串
        String msg = "hello " + type;
        try {

            // 声明交换机 exName type
            channel.exchangeDeclare(exName, type);
            // 声明队列，多个队列同时绑定一个fanout交换机
            channel.queueDeclare(q1, false, false, false, null);
            channel.queueDeclare(q2, false, false, false, null);
            // 绑定
            channel.queueBind(q1, exName, "beijing");
            channel.queueBind(q1, exName, "shenzhen");
            channel.queueBind(q1, exName, "guangzhou");
            channel.queueBind(q2, exName, "shanghai");
            // 发送消息
            channel.basicPublish(exName, "shenzhen", null, msg.getBytes());
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }
}
